<?php


namespace App\Services\Tools;

use App\Exceptions\BasicException;
use App\Repositories\LogRepository;
use Illuminate\Support\Facades\Log;

class QJAesService
{
    /**
     * 加密方式 https://doc.guangzhi3.com/pay/api/sign.html
     * @var string 秘钥
     * OPENSSL_ALGO_SHA256_RSA key PKCS8,长度为2048
     */
    protected $method;


    /**
     * @var string  公共的key  使用 加签就是 公钥  负责私钥
     */
    protected $Key;

    /**
     * @var array
     */
    protected $params;

    public function __construct($Key, $params = [], $method = 'OPENSSL_ALGO_SHA256')
    {
        if (empty($Key)) {
            throw new BasicException(-1, '秘钥不能为空');
        }
        $this->Key = $Key;
        $this->params = $params;
        $this->method = $method;
    }

    /**
     * 加签
     */
    public function signature()
    {
        $sign_data = base64_encode(json_encode($this->params));
//        Log::info("data: ".$sign_data);
        $key = "-----BEGIN PRIVATE KEY-----\n" . $this->Key . "\n-----END PRIVATE KEY-----";
        if (!openssl_sign($sign_data, $signature, $key, OPENSSL_ALGO_SHA256)) {
            throw new BasicException(-1, '加签失败!');
        }
        return base64_encode($signature);
    }

    /**
     * 验签
     * @param $sign  数据签名字符串
     * @param $bizStr json格式请求参数，使用Base64 encode 之后的字符串，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递
     * @return int
     */
    public function signCheck($sign, $bizStr)
    {
        $key = "-----BEGIN PUBLIC KEY-----\n" . $this->Key . "\n-----END PUBLIC KEY-----";
        $signature = base64_decode($sign);
        return openssl_verify($bizStr, $signature, $key, $this->method);

//        if ($is_valid !== 1) {
//            throw new BasicException(-1, '签名验证失败！');
//        }
//        return [
//            'data' => b
//       ase64_decode($bizStr),
//            'is_valid' => $is_valid
//        ];
    }

}
